import wx
import wx.grid
from connect import one_query
from frames import *
from helper_func import *

class Grid(GridFrame):
    col_names = ''
    table_name = ''

    def delete(self, event):
        wx.Yield()
        i = get_input()
        s = f"DELETE FROM [{self.table_name}] WHERE id = '{i}';"
        try:
            one_query(s)
            wx.MessageBox('删除完成', '成功', wx.ICON_INFORMATION)
            self.refresh()
        except:
            wx.MessageBox('数据有误，可能是有依赖项导致的，请重试', '失败', wx.ICON_WARNING)

    def add(self, event):
        wx.Yield()
        x = get_item(self.col_names).split(',')
        col, inp = [], []
        for i in range(len(self.col_names)):
            val = x[i].strip()
            if val != '':
                col.append(self.col_names[i])
                inp.append(f"'{val}'")
        s = f"INSERT INTO [{self.table_name}] ({','.join(col)}) VALUES ({','.join(inp)});"
        try:
            one_query(s)
            wx.MessageBox('添加完成', '成功', wx.ICON_INFORMATION)
            self.refresh()
        except:
            wx.MessageBox('数据有误，请重试', '失败', wx.ICON_WARNING)

    def mod(self, event):
        wx.Yield()
        i = get_input().strip()
        s = f"SELECT * FROM [{self.table_name}] WHERE id = '{i}';"
        try:
            data = one_query(s)[0][:-1]
        except:
            wx.MessageBox('该ID不存在', '错误', wx.ICON_ERROR)
            return
        data = mod_item(self.col_names[:-1], data)
        data = [f"'{x.strip()}'" for x in data.split(',')]
        t = ', '.join([f"{x}={y}" for x, y in zip(self.col_names[:-1], data)])
        s = f"UPDATE [{self.table_name}] SET {t}, add_time = CURRENT_TIMESTAMP WHERE id = '{i}';"
        try:
            one_query(s)
            wx.MessageBox('修改完成', '成功', wx.ICON_INFORMATION)
            self.refresh()
        except:
            wx.MessageBox('修改失败', '错误', wx.ICON_ERROR)

    def refresh(self):
        s = f"SELECT {','.join(self.col_names)} FROM [{self.table_name}];"
        data = one_query(s)
        table = Table(head=self.col_names, body=data, changeable=True)
        self.m_grid.SetTable(table=table, takeOwnership=True)
        self.m_grid.AutoSize()
        self.Layout()

def show(col_names: tuple[str], table_name: str):
    apps = wx.App()
    frame = Grid(None)
    frame.col_names = col_names
    frame.table_name = table_name
    s = f"SELECT {','.join(col_names)} FROM [{table_name}];"
    data = one_query(s)
    table = Table(head=col_names, body=data, changeable=True)
    frame.m_grid.SetTable(table=table, takeOwnership=True)
    frame.m_grid.AutoSize()
    frame.Show()
    apps.MainLoop()

if __name__ == '__main__':
    col_names = ('id', 'name', 'place_of_production', 'price', 'companyid', 'userid', 'add_time')
    table_name = 'goods'
    show(col_names, table_name)
